import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CompletionServiceExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
        // 提交三个任务给线程池处理
        for (int i = 1; i <= 3; i++) {
            int taskId = i;
            completionService.submit(() -> {
                // 模拟任务的处理
                Thread.sleep(new Random().nextInt(5) * 1000);
                return taskId;
            });
        }
        // 获取任务的处理结果
        for (int i = 1; i <= 3; i++) {
            try {
                // take()方法会阻塞等待，知道有任务完成并返回对应的Future对象
                Future<Integer> future = completionService.take();
                int result = future.get(); // 获取任务的结果
                System.out.println("Task " + result + " completed");
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            executorService.shutdown();
        }
        List<Callable<Integer>> tasks = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            tasks.add(() -> {
                Random random = new Random();
                int second = random.nextInt(10);
                Thread.sleep(second * 1000);
                return second;
            });
        }
        ExecutorService executorService2 = Executors.newFixedThreadPool(10);
        try {
            List<Future<Integer>> futures = executorService2.invokeAll(tasks);
            for (int i = 0;i < futures.size();i++) {
                System.out.println(futures.get(i).get());
            }
            executorService.shutdown();
        } catch (InterruptedException | ExecutionException ex) {
            
        }
    }
}
